export class MarkdownMenuNode {
    constructor(isRoot: boolean) {
        this.isRoot = isRoot;
    }

    isRoot = false;

    /**
     * Markdown目录，只在root节点才有值
     */
    mdDir?: string;

    /**
     * 当前节点的README.md文件内容
     */
    readme?: string;

    /**
     * 当前路径
     */
    paths?: string;

    /**
     * 子节点
     */
    nodes?: Map<string, MarkdownMenuNode>;

    /**
     * 当前节点下的文档
     */
    items?: Map<string, string>;

    used = false;

    public static getMarkdownDocs(markdownMaps: Map<string, string>): MarkdownMenuNode {
        const root = new MarkdownMenuNode(true);
        for (const key of Object.keys(markdownMaps)) {
            const paths = key.split('/');
            let childrenNode = root;
            for (let i = 1; i < paths.length; ++i) {
                const path = paths[i];
                if (i === paths.length - 1) {
                    // 已经是最后一级了
                    if (path === 'README') {
                        childrenNode.readme = markdownMaps[key];
                    } else {
                        if (!childrenNode.items) {
                            childrenNode.items = new Map();
                        }
                        childrenNode.items.set(path, markdownMaps[key]);
                    }
                    continue;
                }

                if (!childrenNode.nodes) {
                    childrenNode.nodes = new Map();
                }

                if (childrenNode.nodes.has(path)) {
                    childrenNode = <MarkdownMenuNode>childrenNode.nodes.get(path);
                } else {
                    const node = new MarkdownMenuNode(false);
                    node.paths = paths.slice(0, i + 1).join('/');
                    childrenNode.nodes.set(path, node);
                    childrenNode = node;
                }
            }
        }
        return root;
    }

    public getNode(key: string): MarkdownMenuNode {
        if (!this.nodes) {
            return null;
        }

        return this.nodes ? this.nodes.get(key) : null;
    }

    public getMdNodes(): MarkdownMenuNode {
        const mdNodeName = this.getMdDirName();
        if (!mdNodeName || !this.nodes) {
            return null;
        }
        return <MarkdownMenuNode>this.nodes.get(mdNodeName);
    }

    public getMdDirName(): string {
        if (!this.isRoot) {
            return null;
        }
        if (this.mdDir) {
            return this.mdDir;
        }
        let mdDirName = null;

        if (this.nodes) {
            this.nodes.forEach(((value, key) => {
                mdDirName = key;
            }));
        }
        return mdDirName;
    }
}
